package com.chenjun.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


import net.sf.json.JSONObject;

public class GetMethodUtil {
	
	private static String EMPTY = "";
	private static final String URL_PARAM_CONNECT_FLAG = "&";
	
	/**
	 * 发起GET请求
	 * url 为api请求地址
	 * param 为下方getUrl方法转换后的数据字符
	 * */
	public static JSONObject getMethod(String url,String param){
		JSONObject json;
		BufferedReader br = null;
		URL httpUrl = null;
		try {
			if(!url.equals(null) && !url.equals("")){
				if(url.split("\\?").length>1){
					httpUrl = new URL(url+"&"+param);
				}else{
					httpUrl = new URL(url+"?"+param);
				}
			}
			
			URLConnection connection = httpUrl.openConnection();
			connection.setConnectTimeout(1000000);
			connection.setReadTimeout(1000000);
			InputStream is = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append("\n");
			}
			json = JSONObject.fromObject(sb.toString());
		} catch (Throwable ex) {
			return null;
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// IGNORED
				}
			}
		}
		
		return json;
	}
	
	/**
	 * 拼装url参数
	 * map为查询参数
	 * valueEnc 字符编码 utf-8
	 * */
	public static String getUrl(Map<String, String> map, String valueEnc) {  
         
	        if (null == map || map.keySet().size() == 0) {  
	            return (EMPTY);  
	        }  
	        StringBuffer url = new StringBuffer();  
	        Set<String> keys = map.keySet();  
	        for (Iterator<String> it = keys.iterator(); it.hasNext();) {  
	            String key = it.next();  
	            if (map.containsKey(key)) {  
	                String val = map.get(key);  
	                String str = val != null ? val : EMPTY;  
	                try {  
	                    str = URLEncoder.encode(str, valueEnc);  
	                } catch (UnsupportedEncodingException e) {  
	                    e.printStackTrace();  
	                }  
	                url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);  
	            }  
	        }  
	        String strURL = EMPTY;  
	        strURL = url.toString();  
	        if (URL_PARAM_CONNECT_FLAG.equals(EMPTY + strURL.charAt(strURL.length() - 1))) {  
	            strURL = strURL.substring(0, strURL.length() - 1);  
	        }  
	          
	        return (strURL);  
	    }  
}
